package com.farewell.blog.controller.admin;

import com.baomidou.mybatisplus.plugins.Page;
import com.farewell.blog.entity.QueryBean;
import com.farewell.blog.pojo.Type;
import com.farewell.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @author Farewell
 * @date 2021/2/7
 */
@Controller
@RequestMapping("/admin")
public class TypesController {
    @Autowired
    private TypeService typeService;

    @RequestMapping("/types")
    public String listType(Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum) {
        QueryBean queryBean = new QueryBean(pageNum, 10, null);
        Page<Type> pageData = typeService.listType(queryBean);
        model.addAttribute("pageData", pageData);
        return "admin/types";
    }

    @GetMapping("/types/input")
    public String input() {
        return "admin/types-input";
    }

    @PostMapping("/types/save/{id}")
    public String saveType(@PathVariable Long id, Type type, RedirectAttributes redirectAttributes) {
        try {
            if (typeService.getTypeByName(type) != null) {
                throw new Exception();
            }
            typeService.updateType(id, type);
            redirectAttributes.addFlashAttribute("message", "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "操作失败, 数据库中已经有同名分类");
        }
        return "redirect:/admin/types";
    }

    @PostMapping("/types/save")
    public String saveType(Type type, RedirectAttributes redirectAttributes) {
        try {
            if (typeService.getTypeByName(type) != null) {
                throw new Exception();
            }
            typeService.saveType(type);
            redirectAttributes.addFlashAttribute("message", "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "操作失败, 数据库中已经有同名分类");
        }
        return "redirect:/admin/types";
    }

    @GetMapping("/types/{id}/input")
    public String editInput(@PathVariable("id") Long id, Model model) {
        model.addAttribute("type", typeService.getTypeByName(id));
        return "admin/types-input-s";
    }

    @GetMapping("/types/{id}/delete")
    public String deleteType(@PathVariable("id") Long id, RedirectAttributes attributes) {
        try {
            typeService.deleteType(id);
            attributes.addFlashAttribute("message", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            attributes.addFlashAttribute("message", "删除失败，请稍后再试");
        }
        return "redirect:/admin/types";
    }
}
